package com.zgroup.common;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.displaytag.pagination.PaginatedList;
import org.displaytag.util.DefaultRequestHelper;
import org.displaytag.util.Href;
import org.displaytag.util.RequestHelper;

public class DicUtils {

    public static String showDictionay(HttpServletRequest request, HttpServletResponse response, PaginatedList paginatedList, boolean onSelect) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        if (paginatedList.getFullListSize() == 0) {
            return "";
        }
        String formSource = request.getParameter("formSource");
        String[] formTarget = request.getParameterValues("formTarget");
        if (formTarget == null) {
            formTarget = new String[0];
        }
        String[] javaTarget = request.getParameterValues("javaTarget");
        if (javaTarget == null) {
            javaTarget = new String[0];
        }
        String[] javaSource = request.getParameterValues("javaSource");
        if (javaSource == null) {
            javaSource = new String[0];
        }
        String width = request.getParameter("width");
        if (CheckUtils.isEmpty(width)) {
            width = "100%";
        }
        String param = request.getParameter("param");

//		String parent=request.getParameter("parent");
//		if(parent==null||"null".equals(parent)){
//			parent="";
//		}
        // onselect触发时，回调函数名
        String handle = request.getParameter("handle");
        String entityName = request.getParameter("entityName");

        String page = request.getParameter("page");
        int pageNumber = 1;
        if (page != null) {
            pageNumber = Integer.parseInt(page);
        }
        String searchString = request.getParameter("sourceValue");
        String method = request.getParameter("method");
        String formName = request.getParameter("formName");

//          response.setContentType("text/html; charset=UTF-8");
//	    response.setHeader("Cache-Control", "no-cache");
//	    PrintWriter out = response.getWriter();
        int totalPage = (paginatedList.getFullListSize() % paginatedList.getObjectsPerPage()) == 0 ? (paginatedList.getFullListSize() / paginatedList.getObjectsPerPage())
                : (paginatedList.getFullListSize() / paginatedList.getObjectsPerPage()) + 1;
        //out.println("<table id='DIC_CAPXOUS_"+formSource+"' cellpadding='2' cellspacing='0' width='"+width+"'>");
        StringBuffer buffer = new StringBuffer();
        List list = paginatedList.getList();

        buffer.append("<table id='DIC_CAPXOUS_" + formSource + "' cellpadding='2' cellspacing='0' width='" + width + "'>");

        for (int k = 0; k < list.size(); k++) {
            //out.write("\r\n");
            buffer.append("\r\n");
            //out.write("        \r\n");
            buffer.append("        \r\n");
            Map record = (Map) list.get(k);
            Object value = record.get("DM");
            if (onSelect) {
                //out.write("        <tr  onselect=\"");
                buffer.append("        <tr ");
                buffer.append(" content=\"");
                buffer.append(record.get("MC"));
                buffer.append("\" ");
                buffer.append(" code=\"");
                buffer.append(record.get("DM"));
                buffer.append("\"");
                buffer.append(" onselect=\"");
                for (int i = 0; i < formTarget.length; i++) {
                    buffer.append("document.getElementById('");
                    buffer.append(formTarget[i]);
                    buffer.append("')");
                    buffer.append(".value='");
                    if (value == null) {
                        value = "";
                    }
                    //out.print(value.toString());
                    buffer.append(value.toString());
                    //out.write('\'');
                    buffer.append('\'');
                    //out.write(';');
                    buffer.append(';');
                }
                if (value != null && value != "") {
                    buffer.append("document.getElementById('");
                    buffer.append(formSource);
                    buffer.append("')");
                    buffer.append(".value='");
                    value = record.get("MC");
                    if (value == null) {
                        value = "";
                    }
                    //out.print(value.toString());
                    buffer.append(value.toString());
                    //out.write('\'');
                    buffer.append('\'');
                    //out.write(';');
                    buffer.append(';');
                } else {
                    value = record.get("MC");
                }

                if (handle != null && handle.length() > 0) {
                    if (param != null && param.length() > 0) {
                        //out.write(handle+"('"+record.get(param)+"');");
                        buffer.append(handle + "('" + record.get(param) + "');");
                    } else {
                        //out.write(handle+"('"+record.get("DM")+"');");
                        buffer.append(handle + "('" + record.get("DM") + "');");
                    }
                }
                //out.write("\">\r\n");
                buffer.append("\">\r\n");
            } else {
                //out.write("        <tr onselect=\"return false;\">\r\n");
                buffer.append("        <tr onselect=\"return false;\">\r\n");
            }
            //out.write("\t\t<td style=\"text-align:left;padding-left:3px;text-align:left;\">");
            buffer.append("\t\t<td style=\"text-align:left;padding-left:3px;text-align:left;\">");
            for (int i = 1; i < javaSource.length; i++) {
                Object o = record.get("MC");
                if (o == null) {
                    o = "";
                }
                //out.print(o.toString());
                buffer.append(o.toString());
            }

            //out.println(value);
            buffer.append(value);
            //out.write("</td>\r\n");
            buffer.append("</td>\r\n");

            String cnt = (String) record.get("CNT");
            if (cnt != null) {
                //out.write("\t\t<td align='right' style=\"text-align:right;font-size:10px;padding:0 10px;color:green;overflow:hidden;\">");
                buffer.append("\t\t<td align='right' style=\"text-align:right;font-size:10px;padding:0 10px;color:green;overflow:hidden;\">");
                //out.println("约"+cnt+"条");
                buffer.append("约" + cnt + "条");
                //out.write("</td>\r\n");
                buffer.append("</td>\r\n");
            }

            //out.write("    \t<td><img src=\""+baseurl+"/images/image.png\"></td>\r\n");
            //out.write("\t</tr>\r\n");
            buffer.append("\t</tr>\r\n");
        }
        //out.println("</table>");// end table
        buffer.append("</table>");
        //System.out.println(buffer);
        String baseurl = request.getContextPath();
        RequestHelper requestHelper = new DefaultRequestHelper(request, response);
        Href href = requestHelper.getHref();
        href.removeParameter("page");
        if (totalPage > pageNumber) {
            href.addParameter("page", pageNumber + 1);
            //out.print("<a ajaxHref='");
            buffer.append("<a ajaxHref='");
            buffer.append(href);
            //System.out.println("ajaxHref:"+href);
            //out.print("' style='float:right;cursor:hand'  class='page_down'><img src=\""+baseurl+"/image/nextpage.gif\"/></a>");
            buffer.append("' style='float:right;cursor:hand'  class='page_down'><img src=\"" + baseurl + "/images/nextpage.gif\"/></a>");
        }
        if (pageNumber > 1) {
            href.addParameter("page", pageNumber - 1);
            //out.print("<a ajaxHref='");
            buffer.append("<a ajaxHref='");
            buffer.append(href);
            //System.out.println("ajaxHref:"+href);
            //out.print("' style='float:left;cursor:hand'><img src=\""+baseurl+"/image/previouspage.gif\"/></a>");
            buffer.append("' style='float:left;cursor:hand'><img src=\"" + baseurl + "/images/previouspage.gif\"/></a>");
        }

        if (totalPage > 1) {
            //out.print("<a style='float:left;'>&nbsp;&nbsp;共"+paginatedList.getFullListSize()+"条/"+totalPage+"页&nbsp;当前第"+pageNumber+"页</a>");
            buffer.append("<a style='float:left;'>&nbsp;&nbsp;共" + paginatedList.getFullListSize() + "条/" + totalPage + "页&nbsp;当前第" + pageNumber + "页</a>");
        }

        //out.close();
        return buffer.toString();
    }

    public static PaginationAdapter adapterDic(List list, String parentId, String searchString, int pageNumber) {
        return adapterDic(list, parentId, searchString, pageNumber, "");
    }

    public static PaginationAdapter adapterDic(List list, String parentId, String searchString, int pageNumber, String filter) {
        Comparator c = null;
        if ("ge".equals(filter)) {
            c = new Comparator() {
                public int compare(Object o1, Object o2) {
                    String s1 = (String) o1;
                    String s2 = (String) o2;
                    if (s1.compareTo(s2) >= 0) {
                        return 1;
                    }
                    return 0;
                }
            };
        } else if ("le".equals(filter)) {
            c = new Comparator() {
                public int compare(Object o1, Object o2) {
                    String s1 = (String) o1;
                    String s2 = (String) o2;
                    if (s2.compareTo(s1) >= 0) {
                        return 1;
                    }
                    return 0;
                }
            };
        } else if ("ne".equals(filter)) {
            c = new Comparator() {
                public int compare(Object o1, Object o2) {
                    String s1 = (String) o1;
                    String s2 = (String) o2;
                    if (!s1.equals(s2)) {
                        return 1;
                    }
                    return 0;
                }
            };
        } else {
            c = new Comparator() {
                public int compare(Object o1, Object o2) {
                    String s1 = (String) o1;
                    String s2 = (String) o2;
                    if (s1.startsWith(s2)) {
                        return 1;
                    }
                    return 0;
                }
            };
        }
        PaginationAdapter paginationList = new PaginationAdapter();
        if (list == null || list.isEmpty()) {
            return paginationList;
        }
        final String DM_ITEM = "DM";
        final String MC_ITEM = "MC";
        final String PY_ITEM = "PY";
        List searchResult = new ArrayList();
        if (CheckUtils.isEmpty(searchString)) {
            if (!CheckUtils.isEmpty(parentId)) {
                Iterator iter = list.iterator();
                while (iter.hasNext()) {
                    Map dic = (Map) iter.next();
                    String value = String.valueOf(dic.get(DM_ITEM));
                    if (value != null) {
                        String[] parents = parentId.split(",");
                        for (int i = 0; i < parents.length; i++) {
                            if (c.compare(value, parents[i]) > 0) {
                                searchResult.add(dic);
                            }
                        }
                    }
                }
            } else {
                searchResult = list;
            }
        } else {
            Iterator iter = list.iterator();
            if (searchString.matches("[a-zA-Z]*")) {
                while (iter.hasNext()) {
                    Map dic = (Map) iter.next();
                    String value = String.valueOf(dic.get(DM_ITEM));
                    String pinyin = (String) dic.get(PY_ITEM);
                    if (pinyin != null && pinyin.toLowerCase().startsWith(searchString.toLowerCase())) {
                        if (parentId != null && !parentId.equals("")) {
                            if (value != null) {
                                String[] parents = parentId.split(",");
                                for (int i = 0; i < parents.length; i++) {
                                    if (c.compare(value, parents[i]) > 0) {
                                        searchResult.add(dic);
                                    }
                                }
                            }
//				    if(dic.getDm()!=null&&dic.getDm().startsWith(parentId)){
//				    	searchResult.add(dic);
//				    }
                        } else {
                            searchResult.add(dic);
                        }
                    }
                }
            } else if (searchString.matches("[0-9]*")) {
                while (iter.hasNext()) {
                    Map dic = (Map) iter.next();
                    String value = String.valueOf(dic.get(DM_ITEM));
                    if (value != null && value.toLowerCase().startsWith(searchString.toLowerCase())) {
                        if (parentId != null && !parentId.equals("")) {
                            if (value != null) {
                                String[] parents = parentId.split(",");
                                for (int i = 0; i < parents.length; i++) {
                                    if (c.compare(value, parents[i]) > 0) {
                                        searchResult.add(dic);
                                    }
                                }
                            }
                        } else {
                            searchResult.add(dic);
                        }
                    }
                }
            } else {
                while (iter.hasNext()) {
                    Map dic = (Map) iter.next();
                    String value = String.valueOf(dic.get(DM_ITEM));
                    String mcValue = (String) dic.get(MC_ITEM);
                    if (mcValue != null && mcValue.toLowerCase().startsWith(searchString.toLowerCase())) {
                        if (parentId != null && !parentId.equals("")) {
                            if (value != null) {
                                String[] parents = parentId.split(",");
                                for (int i = 0; i < parents.length; i++) {
                                    if (c.compare(value, parents[i]) > 0) {
                                        searchResult.add(dic);
                                    }
                                }
                            }
                        } else {
                            searchResult.add(dic);
                        }
                    }
                }
            }
        }
        if (searchResult.size() > paginationList.getObjectsPerPage()) {
            paginationList.setFullListSize(searchResult.size());
            int fromIndex = paginationList.getObjectsPerPage() * (pageNumber - 1);
            int toIndex = paginationList.getObjectsPerPage() * (pageNumber) > searchResult.size() ? searchResult.size() : paginationList.getObjectsPerPage() * (pageNumber);
            paginationList.setList(searchResult.subList(fromIndex, toIndex));
            paginationList.setPageNumber(pageNumber);
        } else {
            paginationList.setFullListSize(searchResult.size());
            paginationList.setList(searchResult);
            paginationList.setPageNumber(pageNumber);
        }
        return paginationList;
    }

}
